import edge_tts
import json
import os
import re


VOICE = "en-US-ChristopherNeural"
OUTPUT_PATH = "public/voice"
WORDS_FOLDER = os.path.join(OUTPUT_PATH, "words")
SENTENCES_FOLDER = os.path.join(OUTPUT_PATH, "sentences")

# 创建目录
os.makedirs(WORDS_FOLDER, exist_ok=True)
os.makedirs(SENTENCES_FOLDER, exist_ok=True)

# 读取JS文件并提取JSON数据
file_path = "public/data.js"
with open(file_path, 'r', encoding='utf-8') as file:
    content = file.read()
    # 使用正则表达式提取sentenceData数组
    match = re.search(r'const\s+sentenceData\s*=\s*(\[.*?\]);', content, re.DOTALL)
    if not match:
        raise ValueError("未找到sentenceData数组定义")
    data_json = match.group(1)
    sentence_data = json.loads(data_json)

# 处理句子和单词
for item in sentence_data:
    sentence_id = item.get('id', '')
    sentence_text = item.get('sentence', '')
    words = item.get('words', [])

    if sentence_text:
        # 处理句子
        sentence_file_name = f"sentence_{sentence_id}.mp3"
        sentence_output_file = os.path.join(SENTENCES_FOLDER, sentence_file_name)
        communicate = edge_tts.Communicate(sentence_text, VOICE)
        communicate.save_sync(sentence_output_file)
        print(f"生成句子音频: {sentence_output_file}")

    # 处理单词
    for word in words:
        word_with_underscore = word.replace(" ", "_")
        word_output_file = os.path.join(WORDS_FOLDER, f"{word_with_underscore}.mp3")
        communicate = edge_tts.Communicate(word, VOICE)
        communicate.save_sync(word_output_file)
        print(f"生成单词音频: {word_output_file}")